#include "broadthread.h"
#include <glog/logging.h>
BroadThread::BroadThread(QObject *parent)
    : QThread{parent},m_udpSocket(nullptr),m_port(2002),m_running(false)
{

}

BroadThread::~BroadThread()
{
    if (m_udpSocket)
    {
        //m_udpSocket->abort();
        //delete m_udpSocket;
        m_udpSocket = nullptr;
    }
    quit();
    wait();
}

void BroadThread::setPort(quint16 port)
{
    this->m_port = port;
}

quint16 BroadThread::getPort() const
{
    return m_port;
}

void BroadThread::run()
{
    m_udpSocket = new QUdpSocket();

    if(!m_udpSocket->bind(QHostAddress::AnyIPv4,m_port,QUdpSocket::ShareAddress|QUdpSocket::ReuseAddressHint))
    {
        qDebug()<<"绑定失败，端口:"<<m_port;
        return;
    }

    while(!this->isInterruptionRequested())
    {
        while(m_udpSocket->hasPendingDatagrams())
        {
            QByteArray datagram;
            datagram.resize(m_udpSocket->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;
            m_udpSocket->readDatagram(datagram.data(),datagram.size(),&sender,&senderPort);
            emit datagramReceived(datagram,sender);
            LOG(INFO) << "udp recv: " << qPrintable(QString(datagram.toHex().toUpper()));
        }
    }
    //m_udpSocket->close();
    //delete m_udpSocket;
    //m_udpSocket = nullptr;
}
